<script lang="ts">
export default {
  name: "RecordEntityTable"
}
</script>

<template>
  <!-- 数据表单 -->
  <el-table
      ref="dataTableRef"
      v-loading="loading"
      :data="entityList"
      border
      highlight-current-row
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
  >
    <el-table-column align="center" min-width="40" type="selection"/>
    <el-table-column label="边缘ID" prop="edgeId" width="180"/>
    <el-table-column :formatter="formatDate4elTableColumn" align="center" label="云端创建时间" prop="createTime" width="180"/>
    <el-table-column :formatter="formatDate4elTableColumn" align="center" label="云端更新时间" prop="updateTime" width="180"/>


    <el-table-column align="center" label="记录数值">
      <!-- 表单头：动态列 -->
      <el-table-column
          v-for="(item, index) in header"
          :key="index"
          :label="item.label"
          :type="item.type"
          align="center"
          width="180"
      >
        <!-- 行数据：json和非json格式 -->
        <template v-if="item.type==='expand'" #default="scope">
          <el-form-item>
            <el-input v-model="scope.row.values[item.label]" :autosize="{ minRows: 1, maxRows: 100 }" :readonly="true"
                      type="textarea"/>
          </el-form-item>
        </template>
        <template v-else #default="scope">
          <span>{{ scope.row.values[item.label] }}</span>
        </template>

      </el-table-column>
    </el-table-column>

  </el-table>

  <!-- 分页工具条 -->
  <pagination v-if="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum" :total="total"
              @pagination="handleQuery"/>
</template>

<script lang="ts" setup>
import {onMounted, reactive, toRefs} from "vue";

import {
  listRecordPages,
} from "@/api/cloud/table/record";

import {formatDate4elTableColumn, formatDate4elTableColumn2} from '@/utils/formatter';
import {RecordQueryParam, ValueHeader} from "@/api/cloud/table/record/types";
import {EntityFiled, EntityTable} from "@/api/cloud/table/schema/types";
import {getAttribute, setAttribute} from "@/utils/objutil";

const emit = defineEmits(['rowClick', 'update', 'delete']);// 定义组件的事件通知

/**
 * 对外声明接口：父页面可以调用它
 */
defineExpose({setEntity, refreshTable, getIds, getEntities});

// 数据状态：定义
let dataState = reactive({
  // 页面转载状态
  loading: false,
  // 选中ID数组
  ids: [],
  // 记录总数
  total: 0,
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  // 字段信息
  table: {} as EntityTable,
  // 存放动态列
  header: [] as ValueHeader[],
  // json列的数量
  jsonCount: 0,
  // 查询参数
  queryParams: {pageNum: 1, pageSize: 10} as RecordQueryParam,
  // 实体数据
  entityList: [] as Entity[],
});

// 数据状态：双向引用
const {
  // 页面转载状态
  loading,
  // 字段信息
  table,
  // 存放动态列
  header,
  // json列的数量
  jsonCount,
  // 查询参数
  queryParams,
  // 实体数据
  entityList,
  // 记录总数
  total,
} = toRefs(dataState);

/**
 * 捕获列表中的选择变化
 * @taskParam selection
 */
function handleSelectionChange(selection: any) {
  dataState.ids = selection.map((item: any) => item.id);
  dataState.single = selection.length !== 1;
  dataState.multiple = !selection.length;
}

/**
 * 捕获列表中的行选择
 * @taskParam row
 */
function handleRowClick(row: any) {
  emit('rowClick', row);
}

/**
 * 刷新页面信息
 */
function handleQuery() {
  if (dataState.queryParams.entityType === undefined) {
    return;
  }

  dataState.loading = true;

  // 构造查询参数
  let queryParams = {} as RecordQueryParam;
  queryParams.edgeId = dataState.queryParams.edgeId;
  queryParams.entityType = dataState.queryParams.entityType;
  queryParams.pageNum = dataState.queryParams.pageNum;
  queryParams.pageSize = dataState.queryParams.pageSize;
  queryParams.values = {};
  if (dataState.queryParams.fields !== undefined) {
    for (let field of dataState.queryParams.fields) {
      if (field.value === undefined) {
        continue;
      }

      setAttribute(queryParams.values, field.key, field.value);
    }
  }


  // 发出请求
  dataState.entityList = [];
  listRecordPages(queryParams).then(({data}) => {
    data.list.forEach(item => {
      let jsonTxt = '';
      for (let hd of header.value) {
        // 获得字段信息和数值
        let field = getAttribute(table.value.fields, hd.label) as EntityFiled;
        let value = getAttribute(item.values, hd.label);

        // 如果该列是日期格式，那么转换为文本格式
        if (field.format === 'dateTime') {
          // 转换为文本格式
          let txt = formatDate4elTableColumn2(item.values, hd.label);

          // 将文本格式的日期，覆盖原来的属性
          setAttribute(item.values, hd.label, txt);
        }

        if (field.type === 'json') {
          // 转换为文本格式
          let txt = JSON.stringify(value, null, 5);
          if (jsonCount.value == 1) {
            jsonTxt = txt;
          } else {
            if (jsonTxt === '') {
              jsonTxt = field.name + ':\n' + txt;
            } else {
              jsonTxt = jsonTxt + ':\n\n\n' + field.name + ':\n' + txt;
            }
          }

          // 将文本格式的日期，覆盖原来的属性
          setAttribute(item.values, hd.label, jsonTxt);
        }
      }

      dataState.entityList.push(item)
    });

    dataState.total = data.total;
    dataState.loading = false;
  });
}


/**
 * 获得选中的ID
 */
function getIds(): any {
  return dataState.ids;
}

/**
 * 获得实体信息
 */
function getEntities(): any {
  return dataState.entityList;
}

/**
 * 刷新表单
 */
function setEntity(entityType: string, table: EntityTable) {
  dataState.queryParams.entityType = entityType;
  dataState.table = table;

  dataState.header = [] as ValueHeader[];
  for (let field of Object.values(table.fields)) {
    let label = field.name;
    let type = '';

    if (field.type === 'json') {
      type = 'expand';
      jsonCount.value++;
    }
    dataState.header.push({label: label, type: type});
  }


  handleQuery();
}

/**
 * 刷新表单
 */
function refreshTable(queryParams: RecordQueryParam) {
  dataState.queryParams = queryParams;

  handleQuery();
}

/**
 * 响应页面安装：页面的初始化工作
 */
onMounted(async () => {
});


</script>
